#include <rtthread.h>
#include "rtdevice.h"

#define DBG_TAG "led.c"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

// LED引脚定义 在文件中 Libraries/rt_drivers/drv_gpio.c 中查找
#define ALERT_LED_PIN   57     // LED1 引脚 - PB5
#define ALERT_LED_ON    PIN_HIGH
#define ALERT_LED_OFF   PIN_LOW

static int g_led_keeping = 1;

/**
 * @brief  点亮 LED1
 * @param  无
 * @return 无
 */
static int alert_led_on(void)
{
    rt_pin_write(ALERT_LED_PIN, ALERT_LED_ON);
    LOG_D("alert led on");
    return ALERT_LED_ON;
}

/**
 * @brief  关闭 LED1
 * @param  无
 * @return 无
 */
static int alert_led_off(void)
{
    rt_pin_write(ALERT_LED_PIN, ALERT_LED_OFF);
    LOG_D("alert led off");
    return ALERT_LED_OFF;
}

/**
 * @brief  获取 LED1 的状态
 * @param  无
 * @return 无
 */
static int get_alert_led_status(void)
{
    return rt_pin_read(ALERT_LED_PIN);
}

/**
 * @brief  翻转 LED1 电平
 * @param  无
 * @return 无
 */
static int alert_led_toggle(void)
{
    return (get_alert_led_status() == ALERT_LED_OFF) ? alert_led_on() : alert_led_off();
}

int alert_led_stop(void)
{
    g_led_keeping = 0;
}

/**
 * @brief  LED 线程执行函数
 * @param  parameter 线程的入参
 * @return 无
 */
static void alert_led_thread_entry(void *parameter)
{
    rt_sem_t sem = (rt_sem_t)parameter;

    while (1)
    {
        rt_sem_take(sem, RT_WAITING_FOREVER);
        g_led_keeping = 1;
        while (g_led_keeping) {
            alert_led_toggle();
            rt_thread_mdelay(500);
        }
        alert_led_off();
    }
}

/**
 * @brief  初始化 LED
 * @param  无
 * @return 无
 */
int alert_led_init(void *arg)
{
    rt_pin_mode(ALERT_LED_PIN, PIN_MODE_OUTPUT);   // PB5
    rt_pin_write(ALERT_LED_PIN, PIN_LOW);
    rt_pin_mode(ALERT_LED_PIN-1, PIN_MODE_OUTPUT); // PB4
    rt_pin_write(ALERT_LED_PIN-1, PIN_LOW);
    rt_pin_mode(ALERT_LED_PIN-2, PIN_MODE_OUTPUT); // PB3
    rt_pin_write(ALERT_LED_PIN-2, PIN_LOW);

    rt_thread_t thread = rt_thread_create("led_thread", alert_led_thread_entry, arg, 512, 10, 20);
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
        return RT_EOK;
    }
    else
    {
        LOG_E("create led3 thread failed");
        return (-RT_ERROR);
    }
}


